#include "Sort.h"

PrintArray(int* a, int n)
{
	assert(a);

	for (int i = 0; i < n; i++)
		printf("%d ", a[i]);
	putchar('\n');
}

void _MergeSort(int *a, int *tmp, int left, int right)
{
	if (left >= right)
		return;

	int mid = (left + right) / 2;

	_MergeSort(a, tmp, left, mid);
	_MergeSort(a, tmp, mid+1, right);

	int begin1 = left, end1 = mid;
	int begin2 = mid + 1, end2 = right;

	int i = begin1;
	while (begin1 <= end1 && begin2 <= end2)
	{
		if (a[begin1] <= a[begin2])
			tmp[i++] = a[begin1++];
		else
			tmp[i++] = a[begin2++];
	}

	while (begin1 <= end1)
	{
		tmp[i++] = a[begin1++];
	}

	while (begin2 <= end2)
	{
		tmp[i++] = a[begin2++];
	}

	memcpy(a + left, tmp + left, sizeof(a[0])*(right - left + 1));
}

void MergeSort(int* a, int n)
{
	assert(a);

	int* tmp = (int*)malloc(sizeof(a[0]) * n);
	if (tmp == NULL)
	{
		perror("malloc fail");
		exit(EXIT_FAILURE);
	}

	_MergeSort(a, tmp, 0, n - 1);

	free(tmp);
	tmp = NULL;
}

void MergeSortNonR(int* a, int n)
{
	assert(a);

	int* tmp = (int*)malloc(sizeof(a[0]) * n);
	if (tmp == NULL)
	{
		perror("malloc fail");
		exit(EXIT_FAILURE);	
	}

	int gap = 1;
	while (gap < n)
	{
		for (int j = 0; j < n - 1 - gap; j += 2 * gap)
		{
			int begin1 = j, end1 = j + gap - 1;
			int begin2 = j + gap, end2 = j + 2 * gap - 1;

			if (begin2 >= n)
				break;

			if (end2 >= n)
				end2 = n - 1;
				
			int i = begin1;
			while (begin1 <= end1 && begin2 <= end2)
			{
				if (a[begin1] <= a[begin2])
					tmp[i++] = a[begin1++];
				else
					tmp[i++] = a[begin2++];
			}

			while (begin1 <= end1)
			{
				tmp[i++] = a[begin1++];
			}

			while (begin2 <= end2)
			{
				tmp[i++] = a[begin2++];
			}

			memcpy(a + j, tmp + j, sizeof(a[0]) * (end2-j+1));
		}

		gap *= 2;
	}
}

void CountSort(int* a, int n)
{
	assert(a);

	int max = a[0], min = a[0];

	for (int i = 1; i < n; i++)
	{
		if (a[i] > max)
			max = a[i];

		if (a[i] < min)
			min = a[i];
	}

	int range = max - min + 1;
	int* cnt = (int*)calloc(range, sizeof(a[0]));
	if (cnt == NULL)
	{
		perror("malloc fail");
		exit(EXIT_FAILURE);
	}

	for (int i = 0; i < n; i++)
	{
		cnt[a[i]-min]++;
	}

	int j = 0;
	for (int i = 0; i < range; i++)
	{
		while (cnt[i]--)
		{
			a[j++] = i + min;
		}
	}

	free(cnt);
	cnt = NULL;
}
